package com.easyse.easysesecurity.filter;

import com.easyse.common.utils.RedisCache;
import com.easyse.common.utils.RedisKeyUtil;
import com.easyse.easysesecurity.config.JwtUtil;

import com.easyse.easysesecurity.entity.LoginUser;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;


@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    @Autowired
    AuthenticationManager authenticationManager;

    @Autowired
    RedisCache redisCache;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        // 获取token
        String token = request.getHeader("token");
        if(!StringUtils.hasText(token)){
            //token为空 放行
            filterChain.doFilter(request,response);
        //            return;
        }else {
            String userid = "";
            // 解析token
            try {
                Claims claims = JwtUtil.parseJWT(token);
                userid = claims.getSubject();
            } catch (Exception e) {
                e.printStackTrace();
                throw  new RuntimeException("token非法！-!");
            }
            // 放入HostHolder中
//            hostHolder.setUser(Long.parseLong(userid));
            // redis缓存中获取用户id
            LoginUser loginUser = (LoginUser) redisCache.getCacheObject(RedisKeyUtil.getUserKey(Long.parseLong(userid)));


            if(Objects.isNull(loginUser)){
                //没获取到用户信息
                throw new RuntimeException("用户未登录!-！");
            }
            // 存入SecurityContextHolder
            // 必须用三个参数的构造函数

            //TODO 获取权限信息封装到authentication
            //查出用户的role
            //查出role的mune List
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser,null,null);
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);

            // 放行
            filterChain.doFilter(request,response);
        }


    }
}
